<template>
  <div class="wechat">
    <!-- 卡片视图区域 -->
    <div class="wechat_card">
      <!-- 布局 -->
      <el-row :gutter="20" class="wechat_card_head" type="flex">
        <el-col :span="8">
          <!-- 搜索框及添加区域 -->
          <el-input
            placeholder="请输入房间号"
            v-model="queryInfo.query"
            clearable
            @clear="getHouseChangeList"
            size="medium"
            @input="clearData"
          >
            <el-button
              slot="append"
              size="medium"
              icon="el-icon-search"
              @click="getHouseChangeList"
            ></el-button> </el-input
        ></el-col>
        <el-button
          size="medium"
          class="btn_head_medium"
          type="primary"
          @click="addDialogVisible = true"
          icon="el-icon-circle-plus-outline"
          >新增</el-button
        >

        <el-button
          class="btn_head_medium"
          size="medium"
          type="danger"
          @click="removeUserByIds"
          icon="el-icon-remove-outline"
          >删除</el-button
        >
         <!-- 房产状态筛选 -->
        <el-select
          class="select_head_medium"
          size="medium"
          v-model="houseStateValue"
          @change="selectChange"
          clearable
          collapse-tags
          placeholder="按房产状态筛选"
        >
          <el-option
                v-for="item in houseStateList"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              >
              </el-option>
        </el-select>
        <!-- 表格列筛选 -->
        <div class="tools_head">
          <el-popover placement="bottom" trigger="click">
            <el-checkbox-group v-model="colOptions">
              <el-checkbox
                v-for="item in colSelect"
                :label="item"
                :key="item"
                style="display: block; margin: 10px"
              >
              </el-checkbox>
            </el-checkbox-group>
            <div slot="reference">
              <el-tooltip content="筛选列" placement="bottom">
                <el-button size="small" icon="el-icon-menu"></el-button>
              </el-tooltip>
            </div>
            <el-button
              size="small"
              type="text"
              @click="filterFunHandle('allchecked')"
              >全选</el-button
            >
            <el-button
              size="small"
              type="text"
              @click="filterFunHandle('cancel')"
              >取消全选</el-button
            >
          </el-popover>
          <el-tooltip content="导出excel" placement="bottom">
            <el-button
              size="small"
              icon="el-icon-download"
              style="margin-left: 10px"
              @click="handleDownload"
            ></el-button>
          </el-tooltip>
        </div>
      </el-row>
      <!-- 房产变更列表区域 -->
      <el-table
        :data="houseChangeList"
        style="width: 100%"
        height="85%"
        size="small"
        border
        stripe
        :row-key="(row)=>{ return row.id}"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        ref="tableDataRef"
      >
        <el-table-column type="selection" :reserve-selection="true"> </el-table-column>
        <el-table-column
          type="index"
          label="序号"
          v-if="colData[0].istrue"
        ></el-table-column>
        <el-table-column prop="houseNumber" label="房间号" v-if="colData[1].istrue"></el-table-column>
        <el-table-column prop="floorName" label="所属楼栋" v-if="colData[2].istrue"></el-table-column>
        <el-table-column prop="floorUnitName" label="所属单元" v-if="colData[3].istrue"></el-table-column>
        <el-table-column
          prop="inOwnerName"
          label="迁入业主"
          v-if="colData[4].istrue"
        >
        </el-table-column>
        <el-table-column
          prop="outOwnerName"
          label="迁出业主"
          v-if="colData[5].istrue"
        >
        </el-table-column>
        <el-table-column prop="clear" label="费用清算(元)" v-if="colData[6].istrue" width="110px">
        </el-table-column>
        <el-table-column
          prop="divert"
          label="费用转移(元)"
          width="110px"
          v-if="colData[7].istrue"
        >
        </el-table-column>
        <el-table-column
          prop="state"
          label="状态"
          v-if="colData[8].istrue"
          :filters="[
            { text: '自用', value: 0 },
            { text: '出租', value: 1 },
            { text: '出售', value: 2 },
          ]"
          :filter-method="filterTag"
          filter-placement="bottom-end"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state === 0" type="success">自用</el-tag>
            <el-tag v-else-if="scope.row.state === 1" type="danger"
              >出租</el-tag
            >
            <el-tag v-else type="warning">出售</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="addUserId"
          label="添加人"
          v-if="colData[9].istrue"
        ></el-table-column>
        <el-table-column
          prop="addTime"
          label="添加时间"
          width="180px"
          v-if="colData[10].istrue"
        >
        </el-table-column>
        <el-table-column
          prop="momo"
          label="备注"
          v-if="colData[11].istrue"
        ></el-table-column>
        <el-table-column label="操作" width="150px" fixed="right">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加房产变更的对话框 -->
      <el-dialog
        title="添加房产变更信息"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogReset"
      >
        <!-- 内容主题区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
          :inline="true"
        >
          <el-form-item label="房间id" prop="roomId"
            ><el-input v-model="addForm.roomId" placeholder="请输入房间id"></el-input
          ></el-form-item>
          <el-form-item label="迁出业主" prop="moveOutOwnerId">
             <el-select
              v-model="addForm.moveOutOwnerId"
              placeholder="请选择迁出业主"
              class="select"
            >
              <el-option
                v-for="item in moveOutOwnerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="迁入业主" prop="moveInOwnerId">
            <el-select
              v-model="addForm.moveInOwnerList"
              placeholder="请选择迁入业主"
              class="select"
            >
              <el-option
                v-for="item in moveOutOwnerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="费用清算" prop="clear">
            <el-input v-model="addForm.clear"></el-input
          ></el-form-item>
          <el-form-item label="费用转移" prop="divert"
            ><el-input v-model="addForm.divert"></el-input
          ></el-form-item>
          <el-form-item label="状态" prop="state">
            <el-select v-model="addForm.state" placeholder="请选择房产状态" class="select">
              <el-option
                v-for="item in houseStateList"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="momo"
            ><el-input v-model="addForm.momo"></el-input
          ></el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addHouseChange">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改房产变更信息的对话框 -->
      <el-dialog
        title="修改房产变更信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form
          ref="editFormRef"
          :model="editForm"
          label-width="100px"
          :rules="editFormules"
          :inline="true"
        >
          <el-form-item label="房间id" prop="roomId"
            ><el-input v-model="editForm.roomId" disabled></el-input
          ></el-form-item>
          <el-form-item label="迁入业主" prop="moveInOwnerId">
            <el-select
              v-model="editForm.moveInOwnerId"
              placeholder="请选择迁入业主"
              class="select"
            >
              <el-option
                v-for="item in moveOutOwnerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="迁出业主" prop="moveOutOwnerId">
            <el-select
              v-model="editForm.moveOutOwnerId"
              placeholder="请选择迁出业主"
              class="select"
            >
              <el-option
                v-for="item in moveOutOwnerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="费用清算" prop="clear">
            <el-input v-model="editForm.clear"></el-input
          ></el-form-item>
          <el-form-item label="费用转移" prop="divert"
            ><el-input v-model="editForm.divert"></el-input
          ></el-form-item>
          <el-form-item label="状态" prop="state">
            <el-select v-model="editForm.state" placeholder="请选择房产状态" class="select">
              <el-option
                v-for="item in houseStateList"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="momo"
            ><el-input v-model="editForm.momo"></el-input
          ></el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editHouseChange">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.pageNum"
        :page-sizes="[5, 30, 50, 100]"
        :page-size="this.queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    return {
      // 获取房产变更列表的参数对象
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5
      },
      houseChangeList: [],
      houseStateList:[
        { id: 0 , value: '自用' },
        { id: 1 , value: '出租' },
        { id: 2 , value: '出售' }
      ],//房产状态列表
      moveOutOwnerList:[],//业主数据
      houseStateValue:'',//状态下拉框单选
      colData: [
        { title: "序号", istrue: true },
        { title: "房间号", istrue: true },
        { title: "所属楼栋", istrue: true },
        { title: "所属单元", istrue: true },
        { title: "迁入业主", istrue: true },
        { title: "迁出业主", istrue: true },
        { title: "费用清算", istrue: true },
        { title: "费用转移", istrue: true },
        { title: "状态", istrue: true },
        { title: "添加人", istrue: true },
        { title: "添加时间", istrue: true },
        { title: "备注", istrue: true },
      ],
      colOptions: [],//多选框默认全选
      colSelect: [],//所有表头标题,跟多选框组绑定的
      total: 0,
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 添加房产的表单数据
      addForm: {
        roomId: '',
        moveOutOwnerId: '',
        moveInOwnerId: '',
        clear: '',
        divert: '',
        state: '',
        communityId: '',
        addUserId: '',
        addTime: '',
        momo: ''
      },
      //选中行的id数组
      multipleSelection: [],
      idsArray:{
        ids:[]
      },
      // 查询到的编辑房产变更信息
      editForm: {},
      // 添加表单的验证规则对象
      addFormRules: {
        roomId:[
           { required: true, message: '请输入房间号', trigger: 'blur' },
        ],
        moveOutOwnerId:[
           { required: true, message: '请输入迁出业主', trigger: 'blur' },
        ],
        moveInOwnerId:[
           { required: true, message: '请输入迁入业主', trigger: 'blur' },
        ],
        clear:[
           { required: true, message: '请输入费用清算', trigger: 'blur' },
        ],
        divert:[
           { required: true, message: '请输入费用转移', trigger: 'blur' }
        ],
        state:[
          { required: true, message: '请选择房产状态', trigger: 'change' }
        ]
      },
      // 修改房产变更信息表单的验证规则
      editFormules: {
        roomId:[
           { required: true, message: '请输入房间号', trigger: 'blur' },
        ],
        moveOutOwnerId:[
           { required: true, message: '请输入迁出业主', trigger: 'blur' },
        ],
        moveInOwnerId:[
           { required: true, message: '请输入迁入业主', trigger: 'blur' },
        ],
        clear:[
           { required: true, message: '请输入费用清算', trigger: 'blur' },
        ],
        divert:[
           { required: true, message: '请输入费用转移', trigger: 'blur' }
        ],
        state:[
          { required: true, message: '请选择房产状态', trigger: 'change' }
        ]
      }

    }

  },
  created() {
    this.getHouseChangeList()
    var _this = this;
    for (let i = 0; i < _this.colData.length; i++) {
      _this.colSelect.push(_this.colData[i].title);
      if (_this.colData[i].title == '添加人' || _this.colData[i].title == '添加时间') { //初始化不想展示的列可以放在这个条件里
        continue;
      }
      _this.colOptions.push(_this.colData[i].title);
    }
  },
  watch: {
    // 单选列实现
    colOptions(valArr) {
      var arr = this.colSelect.filter(i => valArr.indexOf(i) < 0); // 未选中
      this.colData.filter(i => {
        if (arr.indexOf(i.title) != -1) {
          i.istrue = false;
        } else {
          i.istrue = true;
        }
      });
      this.$nextTick(() => {
        this.$refs.tableDataRef.doLayout();
      });
    }
  },
  methods: {
    // 获取房产变更档案列表
    async getHouseChangeList() {
      this.queryInfo = this.getQueryCondition()
      if(this.queryInfo.condition=='')
        delete this.queryInfo.condition
      const { data: res } = await this.$http.get('BasehousechangeAction/getBasicInfos', { params: this.queryInfo })
      if (!res.success) return this.$message.error('获取房产变更列表失败')
      console.log(res)
      this.houseChangeList = res.rows
      this.total = res.total
      if(this.queryInfo.query!==''){
        var query1 = this.queryInfo.query
        //对列表数据进行过滤(对表格中的外键进行查询，需要使用filter方法)
        this.houseChangeList=res.rows.filter(function(i){ 
          return i.houseNumber===query1 }
        )
        this.total = this.houseChangeList.length
      }
      var queryInfo1={}
      queryInfo1.condition = ` userType=0 `
      const { data: res1 } = await this.$http.post('BaseresidentinfoAction/getBasicInfos',queryInfo1)
      console.log(res1.rows);
      this.moveOutOwnerList = res1.rows;
    },
     async clearData() {
      if (this.queryInfo.query !== '') {
        delete this.queryInfo.condition 
      }
    },
    //点击按钮，添加新房产变更记录
    addHouseChange() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        //给隐藏的input输入框中的添加人addUserId赋值
        this.addForm.addUserId = window.sessionStorage.getItem('userId')
        // 添加时间
        this.addForm.addTime = this.dateFormat()
        const { data: res } = await this.$http.post("BasehousechangeAction/addObject", this.addForm)
        if (!res.success) return this.$message.error('添加房产变更记录失败')
        //关闭对话框
        this.addDialogVisible = false
        //刷新数据列表
        this.getHouseChangeList()
        this.$message.success('添加房产变更记录成功')
      })
    },
    // 展示编辑房产变更记录的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.post("BasehousechangeAction/getObjectById", { id })
      if (!res.success)
        return this.$message.error('查询房产变更记录失败')
      this.editForm = res.rows[0]
      console.log(this.editForm);
      this.editDialogVisible = !this.editDialogVisible
    },

    //点击按钮，修改房产变更记录信息
    editHouseChange() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post("BasehousechangeAction/updateNoNull", this.editForm)
        if (!res.success) return this.$message.error('修改房产变更记录信息失败')
        //关闭对话框
        this.editDialogVisible = false
        //刷新数据列表
        this.getHouseChangeList()
        this.$message.success('修改房产变更记录信息成功')
      })
    },
    filterTag(value, row) {
      return row.state === value;
    },
    // 根据id删除房产变更
    async removeUserById(ids) {
      // 先弹框询问用户是否确定要删除
      const confirmResult = await this.$confirm('此操作将永久删除该房产变更, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // 如果点击取消返回的是字符串cancel
      // 如果点击确认返回的是字符串confirm
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.post("BasehousechangeAction/deleteByIds", { ids })
      console.log(res);
      if (!res.success) {
        return this.$message.error('删除房产变更记录失败')
      }
      this.$message.success('删除房产变更记录成功')
      // 刷新列表
      this.getHouseChangeList()
    },

    //批量删除
    async removeUserByIds() {
      const rows = this.$refs.tableDataRef.selection;
      if (rows.length === 0) {
        this.$message.warning('请选择需要操作的数据')
        return
      }
      else {
        // 先弹框询问用户是否确定要删除
        const confirmResult = await this.$confirm('此操作将永久删除该房产变更记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => {
          return err
        })
        if (confirmResult !== 'confirm') {
          return this.$message.info('取消了删除')
        }
        const { data: res } = await this.$http.post("BasehousechangeAction/deleteByIds",  this.idsArray )
        console.log(res);
        if (!res.success) {
          return this.$message.error('删除房产变更记录失败')
        }
        this.$message.success('删除房产变更记录成功')
        //此时全选框还是选中状态，批量删除后需清除选中状态
        this.$refs.tableDataRef.clearSelection();
        // 刷新列表
        this.getHouseChangeList()
      }

    },
    // 监听修改房产变更对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 监听pageSize改变的事件
    handleSizeChange(newpageSize) {
      // console.log(newpageSize)
      this.queryInfo.pageSize = newpageSize
      // pageSize改变重新拿到房产变更列表
      this.getHouseChangeList()
    },
    // 监听当前页码改变的事件
    handleCurrentChange(newpageNum) {
      // console.log(newpageNum)
      this.queryInfo.pageNum = newpageNum
      this.getHouseChangeList()
    },
    addDialogReset() {
      // 拿到表单的引用进行重置
      this.$refs.addFormRef.resetFields()
    },
     //当多选框选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.idsArray.ids = [] //每次点击需清空原本数组的内容
      this.multipleSelection.map(item => { //遍历数组，把id存进自定义的数组里
        this.idsArray.ids.push(item.id)
      })
      this.idsArray.ids = this.idsArray.ids.join(',')
      // console.log(this.idsArray);
      
    },

     //导出Excel表
    handleDownload(){
      window.open(axios.defaults.baseURL+'/BasehousechangeAction/exportDataToExcel?token='+window.sessionStorage.getItem('token'))
    },
    // 全选或取消全选实现
    filterFunHandle(type, currentItem, index) {
      if (type === 'allchecked') { // 全选
        if (this.colSelect.length === 0) {
          this.colData.forEach((result) => {
            this.colSelect.push(result.title)
          })
          this.colOptions = this.colSelect // 复选框置为复选所有值，全部选择

        } else {
          this.colOptions = this.colSelect // 复选框置为复选所有值，全部选择

        }
      } else if (type === 'cancel') { // 取消全选
        this.colOptions = [] // 复选框置为空，全部不选择

      }
    },
    //工具栏的各种下拉框筛选监听
    async selectChange() {
      this.getHouseChangeList()
    },
    //获取工具栏的各类查询条件：搜索框关键词、筛选框值等
    getQueryCondition() {
      //搜索框筛选
      // var search = `basehousechange.roomId like "%${this.queryInfo.query}%"`;
      // 下拉框筛选
      var houseList = '';
      if (this.houseStateValue !== '') {
        houseList += ` basehousechange.state='${this.houseStateValue}'`;
      }
      this.queryInfo.condition = `${houseList}`;
      return this.queryInfo;
    },
  }
}
</script>
<style lang="less" scoped>
</style>